<script lang="ts" setup>
import type { IUploadSuccessInfo } from '@/api/types/login'
import { storeToRefs } from 'pinia'
import { uploadAvatar } from '@/api/system/user/user'
import { LOGIN_PAGE } from '@/router/config'
import { useThemeStore, useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'
import { useUpload } from '@/utils/uploadFile'

definePage({
  style: {
    navigationBarTitleText: '我的',
  },
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
const themeStore = useThemeStore()
// 使用storeToRefs解构userInfo
const { userInfo } = storeToRefs(userStore)

// #ifndef MP-WEIXIN
const baseUrl = import.meta.env.BASE_URL
const uploadFileUrl = `${baseUrl}/resource/oss/upload`
// 上传头像
async function handleAvatar() {
  uni.chooseImage({
    count: 1,
    success(res) {
      const data = { name: 'avatarfile', filePath: res.tempFilePaths[0] }
      uploadAvatar(data).then((response) => {
        useUserStore().setUserAvatar(response.data.imgUrl)
        uni.showToast({ title: '修改成功', icon: 'success' })
      })
    },
  })
}
// #endif

// 微信小程序下登录
async function handleLogin() {
  // #ifdef MP-WEIXIN
  // 微信登录
  await tokenStore.wxLogin()

  // #endif
  // #ifndef MP-WEIXIN
  uni.navigateTo({
    url: `${LOGIN_PAGE}?redirect=${encodeURIComponent('/pages/mine/index')}`,
  })
  // #endif
}

// #ifdef MP-WEIXIN

// 微信小程序下选择头像事件
function onChooseAvatar(e: any) {
  const baseUrl = import.meta.env.VITE_APP_BASE_API
  const uploadFileUrl = `${baseUrl}/resource/oss/upload` // 上传文件服务器地址
  console.log('选择头像', e.detail)
  const { avatarUrl } = e.detail
  const { run } = useUpload<IUploadSuccessInfo>(
    uploadFileUrl,
    {},
    {
      onSuccess: (res) => {
        console.log('wx头像上传成功', res)
        useUserStore().setUserAvatar(res.url)
      },
    },
    avatarUrl,
  )
  run()
}
// #endif
// #ifdef MP-WEIXIN
// 微信小程序下设置用户名
function getUserInfo(e: any) {
  console.log(e.detail)
}
// #endif

// 切换主题
function handleTheme() {
  if (themeStore.theme === 'light') {
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#131313',
    })
  }
  else {
    uni.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#f8f8f8',
    })
  }
  themeStore.toggleTheme()
}

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清空用户信息
        useTokenStore().logout()
        // 执行退出登录逻辑
        uni.showToast({
          title: '退出登录成功',
          icon: 'success',
        })
        // #ifdef MP-WEIXIN
        // 微信小程序，去首页
        uni.reLaunch({ url: '/pages/index/index' })
        // #endif
        // #ifndef MP-WEIXIN
        // 非微信小程序，去登录页
        uni.navigateTo({ url: LOGIN_PAGE })
        // #endif
      }
    },
  })
}

function handleToInfo() {
  uni.navigateTo({
    url: '/pages/mine/info/index',
  })
}

function handleToPwd() {
  uni.navigateTo({
    url: '/pages/mine/pwd/index',
  })
}
</script>

<template>
  <view class="page">
    <view v-if="tokenStore.hasLogin">
      <wd-card type="rectangle">
        <view>
          <wd-row :gutter="20">
            <wd-col :span="8">
              <!-- #ifdef MP-WEIXIN -->
              <button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <wd-img :width="100" round :height="100" :src="userInfo.user.avatar" custom-class="avatar-wrapper" />
              </button>
              <!-- #endif -->
              <!-- #ifndef MP-WEIXIN -->
              <wd-img :width="100" round :height="100" :src="userInfo.user.avatar" custom-class="avatar-wrapper" @click="handleAvatar" />
              <!-- #endif -->
            </wd-col>
            <wd-col :span="8">
              <view class="user-details">
                <!-- #ifdef MP-WEIXIN -->
                <input
                  v-model="userInfo.user.userName"
                  type="nickname"
                  class="weui-input"
                  placeholder="请输入昵称"
                >
                <!-- #endif -->
                <!-- #ifndef MP-WEIXIN -->
                <view class="username">
                  <view class="page-text">
                    {{ userInfo.user.userName }}
                  </view>
                </view>
                <!-- #endif -->
                <view class="user-id">
                  <view class="page-text">
                    ID: {{ userInfo.user.userId }}
                  </view>
                </view>
              </view>
            </wd-col>
          </wd-row>
        </view>
      </wd-card>
    </view>
    <view class="mt-4">
      <wd-cell-group border>
        <wd-cell v-if="tokenStore.hasLogin" title="编辑资料" size="large" clickable @click="handleToInfo">
          <template #icon>
            <wd-icon name="user" color="#ff0000" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
        <wd-cell v-if="tokenStore.hasLogin" title="修改密码" size="large" clickable @click="handleToPwd">
          <template #icon>
            <wd-icon name="lock-on" color="#ff0000" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
        <wd-cell v-if="themeStore.theme === 'light'" title="深色模式" size="large" clickable @click="handleTheme">
          <template #icon>
            <wd-icon name="info-circle-filled" color="#ff0000" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
        <wd-cell v-if="themeStore.theme === 'dark'" title="浅色模式" size="large" clickable @click="handleTheme">
          <template #icon>
            <wd-icon name="info-circle-filled" color="#ff0000" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
        <wd-cell v-if="tokenStore.hasLogin" title="退出登录" size="large" clickable @click="handleLogout">
          <template #icon>
            <wd-icon name="logout" color="#ff0000" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
        <wd-cell v-else title="登 录" size="large" clickable @click="handleLogin">
          <template #icon>
            <wd-icon name="login" color="#027cf1" size="20px" class="margin-right-sm" />
          </template>
        </wd-cell>
      </wd-cell-group>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.avatar-wrapper {
  width: 160rpx;
  height: 160rpx;
  margin-right: 40rpx;
  overflow: hidden;
  border: 4rpx solid #f5f5f5;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.avatar-button {
  height: 160rpx;
  width: 160rpx;
  padding: 0;
  margin-right: 40rpx;
  overflow: hidden;
  border: 4rpx solid #f5f5f5;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}
.user-details {
  flex: 1;
}

.username {
  margin-bottom: 12rpx;
  font-size: 38rpx;
  font-weight: 600;
  color: #333;
  letter-spacing: 0.5rpx;
}

.user-id {
  font-size: 28rpx;
  color: #666;
}

.user-created {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #999;
}
</style>
